package com.wosai.teach.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.content.ComponentName;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ImageView.ScaleType;

import com.android.agnetty.constant.HttpCst;
import com.android.agnetty.core.AgnettyFutureListener;
import com.android.agnetty.core.AgnettyResult;
import com.android.agnetty.future.http.HttpFuture;
import com.wosai.teach.R;
import com.wosai.teach.adapter.NewPagerAdapter;
import com.wosai.teach.adapter.WhoUsedAdapter;
import com.wosai.teach.dao.InstallDao;
import com.wosai.teach.handler.ExpDetailHandler;
import com.wosai.teach.handler.WhosUsedHandler;
import com.wosai.teach.listener.NewPageChangeListener;
import com.wosai.teach.pojo.Experiment;
import com.wosai.teach.pojo.Install;
import com.wosai.teach.pojo.Pic;
import com.wosai.teach.pojo.WhoUsed;
import com.wosai.teach.thread.LunBoRunnable;
import com.wosai.teach.utils.AppGlobal;
import com.wosai.teach.utils.AppUtil;
import com.wosai.teach.utils.C;
import com.wosai.teach.utils.GodUtils;
import com.wosai.teach.utils.ImageLoaders;
import com.wosai.teach.utils.ListViewUtils;

/**
 * @author : qiumy
 * @e-mail : qiumy@wosaitech.com
 * @date : 2015-5-13 上午9:42:24
 * @desc :
 */
public class ExpDetailAction extends BaseActivity implements OnClickListener {

	private Experiment exp;

	private TextView key, info;

	private ImageView icon;

	private ListView whoUsed;

	private ExpDetailAction self;

	private LinearLayout car_ll;

	private ViewGroup viewGroup;

	private ViewPager viewPager;

	private LunBoRunnable runnable;

	private List<Pic> picList;

	private boolean info_status = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_exp_dtl);
		Intent it = getIntent();
		exp = (Experiment) it.getSerializableExtra("exp");
		setTopTitle("详细信息");
		enableBack(true);
		initView();
		loadSoftInfo();
		AppGlobal.instHandler.setCurAct(this);
	}

	public void initView() {
		icon = (ImageView) this.findViewById(R.id.exp_dtl_icon);
		ImageLoaders.getInstance().displayImage(icon, exp.getIcon1(),
				R.drawable.icon);
		TextView name = (TextView) this.findViewById(R.id.exp_dtl_name);
		name.setText(exp.getExpName());
		TextView ver = (TextView) this.findViewById(R.id.exp_dtl_ver);
		ver.setText("版本：" + exp.getVersionName());
		whoUsed = (ListView) this.findViewById(R.id.exp_dtl_who_used);
		key = (TextView) this.findViewById(R.id.exp_dtl_key);
		key.setText("关键字:加载中");
		info = (TextView) this.findViewById(R.id.exp_dtl_info);
		info.setText("描述：加载中");

		car_ll = (LinearLayout) findViewById(R.id.car_ll);
		viewPager = (ViewPager) findViewById(R.id.car_vp);
		viewGroup = (ViewGroup) findViewById(R.id.car_vg);
		Button bt1 = (Button) this.findViewById(R.id.exp_dtl_bt_install);
		Button bt2 = (Button) this.findViewById(R.id.exp_dtl_bt_open);
		Button bt3 = (Button) this.findViewById(R.id.exp_dtl_bt_uninstall);
		Button bt4 = (Button) this.findViewById(R.id.exp_dtl_bt_update);
		bt1.setOnClickListener(this);
		bt2.setOnClickListener(this);
		bt3.setOnClickListener(this);
		bt4.setOnClickListener(this);
		bt1.setEnabled(false);
		bt2.setEnabled(false);
		bt3.setEnabled(false);
		bt4.setEnabled(false);

		if (exp.getStatus() == C.TEACH_STATUS_INSTALL) {
			// 已安装
			bt2.setEnabled(true);
			bt3.setEnabled(true);
			bt1.setText("已安装");
			if (exp.getVersionCode() < exp.getApkVer()) {
				if (AppGlobal.factory.checkByExp(exp)) {
					bt4.setText("下载中");
				} else {
					bt4.setEnabled(true);
				}
			}
		} else if (exp.getStatus() == C.TEACH_STATUS_LOADOVER) {
			bt1.setText("安装");
			bt1.setEnabled(true);
		} else if (exp.getStatus() == C.TEACH_STATUS_DOWNLOAD) {
			bt1.setText("下载中");
		} else if (exp.getStatus() == C.TEACH_STATUS_NOT_INSTALL) {
			// 未安装
			bt1.setText("下载");
			bt1.setEnabled(true);
		}
	}

	/**
	 * 轮播，活动
	 */
	private void exeCar(Experiment expDtl) {
		picList = new ArrayList<Pic>();
		if (!GodUtils.CheckNull(expDtl.getPicURL1())) {
			Pic pic = new Pic();
			pic.setUrl(expDtl.getPicURL1());
			picList.add(pic);
		}
		if (!GodUtils.CheckNull(expDtl.getPicURL2())) {
			Pic pic = new Pic();
			pic.setUrl(expDtl.getPicURL2());
			picList.add(pic);
		}
		if (!GodUtils.CheckNull(expDtl.getPicURL3())) {
			Pic pic = new Pic();
			pic.setUrl(expDtl.getPicURL3());
			picList.add(pic);
		}
		if (!GodUtils.CheckNull(expDtl.getPicURL4())) {
			Pic pic = new Pic();
			pic.setUrl(expDtl.getPicURL4());
			picList.add(pic);
		}
		if (!GodUtils.CheckNull(expDtl.getPicURL5())) {
			Pic pic = new Pic();
			pic.setUrl(expDtl.getPicURL5());
			picList.add(pic);
		}

		LayoutInflater layIn = LayoutInflater.from(this);
		List<View> viewList = new ArrayList<View>();
		if (GodUtils.CheckNull(picList)) {
			return;
		} else {
			this.car_ll.setVisibility(View.VISIBLE);
			for (Pic pic : picList) {
				View view = layIn.inflate(R.layout.activity_lun_item,
						viewPager, false);
				ImageView iv = (ImageView) view.findViewById(R.id.lun_iv);
				ImageLoaders.getInstance().displayImage(iv, pic.getUrl());
				iv.setScaleType(ScaleType.FIT_XY);
				viewList.add(view);
			}
		}

		NewPagerAdapter adapter = new NewPagerAdapter(viewList);
		viewPager.setAdapter(adapter);

		ImageView[] imageViews = new ImageView[viewList.size()];
		for (int i = 0; i < viewList.size(); i++) {
			ImageView imageView = new ImageView(this);
			imageView.setLayoutParams(new LayoutParams(36, 16));
			imageView.setPadding(10, 0, 10, 0);// 左 上 右 下
			imageViews[i] = imageView;
			if (i == 0) {
				// 默认选中第一张图片
				imageViews[i].setImageResource(R.drawable.point_white);
			} else {
				imageViews[i].setImageResource(R.drawable.point_grey);
			}
			viewGroup.addView(imageViews[i]);
		}
		NewPageChangeListener listener = new NewPageChangeListener(imageViews);
		viewPager.setOnPageChangeListener(listener);

		Handler handler = new Handler();
		runnable = new LunBoRunnable(viewPager, viewList.size(), handler);
		handler.postDelayed(runnable, 4000);
	}

	private void loadSoftInfo() {
		String url = C.HTTP_URL_EXP_DETAIL;
		url = url.replace("{userId}", 0 + "");
		url = url.replace("{expId}", exp.getExpId() + "");
		System.out.println(url);
		self = this;
		new HttpFuture.Builder(this, HttpCst.GET).setUrl(url)
				.setHandler(ExpDetailHandler.class)
				.setListener(new AgnettyFutureListener() {
					@Override
					public void onComplete(AgnettyResult result) {
						super.onComplete(result);
						Object rst = result.getAttach();
						if (rst != null && rst instanceof Experiment) {
							Experiment expDtl = (Experiment) rst;
							key.setText("关键字: " + expDtl.getKeywords());
							info.setText("" + expDtl.getDetailInfo());
							info.setOnClickListener(self);
							exeCar(expDtl);
						}
					}

					@Override
					public void onException(AgnettyResult result) {
						super.onException(result);
					}
				}).execute();

		String url2 = C.HTTP_URL_WHO_USED;
		url2 = url2.replace("{expId}", exp.getExpId() + "");
		url2 = url2.replace("{userId}", 0 + "");
		url2 = url2.replace("{pageSize}", 10 + "");
		url2 = url2.replace("{currentPage}", 1 + "");
		System.out.println(url2);
		new HttpFuture.Builder(this, HttpCst.GET).setUrl(url2)
				.setHandler(WhosUsedHandler.class)
				.setListener(new AgnettyFutureListener() {
					@Override
					public void onComplete(AgnettyResult result) {
						super.onComplete(result);
						Object rst = result.getAttach();
						if (rst != null && rst instanceof List) {
							List<WhoUsed> wuList = (List<WhoUsed>) rst;
							exeWhoUsed(wuList);
						}
					}

					@Override
					public void onException(AgnettyResult result) {
						super.onException(result);
					}
				}).execute();
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	private void exeWhoUsed(List<WhoUsed> wuList) {
		if (GodUtils.CheckNull(wuList)) {
			return;
		}
		this.whoUsed.setVisibility(View.VISIBLE);
		WhoUsedAdapter adapter = new WhoUsedAdapter(this, wuList);
		this.whoUsed.setAdapter(adapter);
		ListViewUtils.setListViewHeightBasedOnChildren(this.whoUsed);
	}

	@Override
	public void onClick(View v) {
		boolean toLogin = AppUtil.toLogin(this);
		switch (v.getId()) {
		case R.id.exp_dtl_bt_open:
			if (toLogin) {
				return;
			}
			Intent intent = new Intent(Intent.ACTION_MAIN);
			intent.addCategory(Intent.CATEGORY_LAUNCHER);
			ComponentName cn = new ComponentName(exp.getApkPackageName(),
					exp.getApkClassName());
			intent.setComponent(cn);
//			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.putExtra("userId", AppGlobal.user.getUserId());
			startActivityForResult(intent, C.REQUEST_CODE_OPEN);
			break;
		case R.id.exp_dtl_bt_uninstall:
			if (toLogin) {
				return;
			}
			Uri packageURI = Uri.parse("package:" + exp.getApkPackageName()); // 包名
			Intent uninstallIntent = new Intent(Intent.ACTION_DELETE,
					packageURI);
			startActivityForResult(uninstallIntent, C.REQUEST_CODE_UNINSTALL);
			break;
		case R.id.exp_dtl_bt_install:
			if (toLogin) {
				return;
			}
			if (exp.getStatus() == C.TEACH_STATUS_LOADOVER) {
				AppUtil.install(this, exp.getExpId());
			} else if (exp.getStatus() == C.TEACH_STATUS_NOT_INSTALL) {
				Button bt = (Button) v;
				if (AppGlobal.factory.checkDownLoad(exp, null, bt)) {
					bt.setText("下载中");
					bt.setEnabled(false);
				}
			}
			break;
		case R.id.exp_dtl_bt_update:
			if (toLogin) {
				return;
			}
			if (exp.getStatus() == C.TEACH_STATUS_LOADOVER) {
				AppUtil.install(this, exp.getExpId());
			} else if (exp.getStatus() == C.TEACH_STATUS_INSTALL) {
				Button bt = (Button) v;
				bt.setText("下载中");
				bt.setEnabled(false);
				AppGlobal.factory.checkDownLoad(exp, null, bt);
			}
			break;
		case R.id.exp_dtl_info:
			if (info_status) { // 收拢
				info_status = false;
				info.setEllipsize(TextUtils.TruncateAt.END);
				info.setLines(3);
			} else { // 展开
				info_status = true;
				info.setEllipsize(null);
				info.setSingleLine(false);
			}
			break;
		default:
			break;
		}
	}

	private void delApk() {
		String sdcard = Environment.getExternalStorageDirectory().getPath();
		File tmpFile = new File(sdcard + "/teach_platform");
		if (!tmpFile.exists()) {
			return;
		}
		String tt[] = exp.getApkURL().split("/");
		String fileName = tt[tt.length - 1];
		String savePath = sdcard + "/teach_platform/" + fileName;
		File apk = new File(savePath);
		if (apk.exists() && apk.isFile()) {
			apk.delete();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == C.REQUEST_CODE_INSTALL) {
			exp.initNative(this);
			if (exp.getVersionCode() >= 1) {
				exp.setStatus(C.TEACH_STATUS_INSTALL);
				exp.save();
			}
		} else if (requestCode == C.REQUEST_CODE_UPDATE) {
			exp.initNative(this);
			if (exp.getVersionCode() >= exp.getApkVer()) {
				exp.setStatus(C.TEACH_STATUS_INSTALL);
				exp.save();
				InstallDao instDao = new InstallDao();
				Install inst = instDao.getInstallByExpId(exp.getExpId());
				inst.delete();
			}
		} else if (requestCode == C.REQUEST_CODE_UNINSTALL) {
			// 成功
			exp.initNative(this);
			if (exp.getVersionCode() == 0) {
				exp.setStatus(C.TEACH_STATUS_NOT_INSTALL);
			}
			// 删除安装包
			delApk();
		}
		initView();
	}
}
